package ch.mse.android.starbucksfinder;

import java.util.LinkedList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

public class StarbucksLocationHandler extends DefaultHandler{

	private List<StarbucksLocation> locations;
	private StarbucksLocation currLoc;
	private Tags currTag;
	
	private enum Tags{
		Adresse,
		Stadt,
		PLZ,
		Name,
		Telefon,
		Lat,
		Long
	}
	
	public List<StarbucksLocation> getParsedData() {
		return locations;
	}
	
	@Override
	public void startDocument(){
		locations = new LinkedList<StarbucksLocation>();
	}
	
	@Override
	public void startElement(String namespaceURI, String localName, String qName, Attributes attrs){
		if(localName.equals("entries")){
			//??
		}else if(localName.equals("row")){
			currLoc = new StarbucksLocation();
		}else if(localName.equals("Adresse")){
			currTag = Tags.Adresse;
		}else if(localName.equals("Stadt")){
			currTag = Tags.Stadt;
		}else if(localName.equals("PLZ")){
			currTag = Tags.PLZ;
		}else if(localName.equals("Name")){
			currTag = Tags.Name;
		}else if(localName.equals("Telefon")){
			currTag = Tags.Telefon;
		}else if(localName.equals("Lat")){
			currTag = Tags.Lat;
		}else if(localName.equals("Long")){
			currTag = Tags.Long;
		}
	}

	@Override
	public void endElement(String namespaceURI, String localName, String qName){
		if(localName.equals("row")){
			locations.add(currLoc);
		}
		currTag = null;
	}
	
	@Override
	public void characters(char[] ch, int start, int length){
		if(currTag == null) return;
		String str = new String(ch, start,length);
		switch(currTag){
		case Adresse:
			currLoc.setAddress(new String(ch, start,length));
			break;
		case Lat:
			currLoc.setLatitude(Float.parseFloat(new String(ch, start,length)));
			break;
		case Long:
			currLoc.setLongitude(Float.parseFloat(new String(ch, start,length)));
			break;
		case Name:
			currLoc.setName(new String(ch, start,length));
			break;
		case PLZ:
			currLoc.setZip(new String(ch, start,length));
			break;
		case Stadt:
			currLoc.setCity(new String(ch, start,length));
			break;
		case Telefon:
			currLoc.setPhone(new String(ch, start,length));
			break;
		}
	}
}
